package models

import (
	"gorm.io/gorm"
)

type Goods struct {
	gorm.Model
	UserId     int     `gorm:"type:int(11);comment:用户id" json:"userId"`
	GoodsTitle string  `gorm:"type:varchar(50);comment:商品标题" json:"goodsTitle"`
	GoodsPrice float64 `gorm:"type:decimal(10,2);comment:商品价格" json:"goodsPrice"`
	GoodsStock int     `gorm:"type:int(11);comment:商品库存" json:"goodsStock"`
	Status     int     `gorm:"type:int(1);default:1;comment:商品状态: 0下架 1上架" json:"status"`
}

// 商品发布
func (g *Goods) Create() error {
	return DB.Debug().Create(&g).Error
}

// 商品列表
func (g *Goods) GetGoodsList(page, pageSize int) (goodsList []*Goods, err error) {
	db := DB.Debug().Model(Goods{})

	//搜索条件
	if g.GoodsTitle == "" {
		err = db.Scopes(Paginate(page, pageSize)).Order("goods_price desc").Find(&goodsList).Error
	}

	err = db.Where("goods_title like ? and status= 1", "%"+g.GoodsTitle+"%").Scopes(Paginate(page, pageSize)).Order("goods_price desc").Find(&goodsList).Error
	return goodsList, err
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// 商品查询
func (g *Goods) GetGoods() error {
	return DB.Debug().Where("id = ? and status = 1", g.ID).Limit(1).Find(&g).Error
}

// 扣减库存
func (g *Goods) UpdateStock() error {
	return DB.Debug().Model(Goods{}).Where("id = ?", g.ID).Updates(&g).Error
}
